package com.ezandroid.module.manager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;

import com.ezandroid.EZAndroidApplication;
import com.ezandroid.library.network.download.IDownController;
import com.ezandroid.library.network.util.NetworkUtil;

import java.util.ArrayList;

public class DownControllerManager {

    /**
     * 监听网络变化
     */
    private BroadcastReceiver mNetworkChangedReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (NetworkUtil.isWifiConnected(context)) {
                dealWifi();
            } else if (NetworkUtil.isMobileConnected(context)) {
                dealGPRS();
            } else {
                dealWithoutInternet();
            }
        }
    };

    private static DownControllerManager mInstance = new DownControllerManager();

    private ArrayList<IDownController> mDownControllers = new ArrayList<IDownController>();

    private DownControllerManager() {
    }

    public static DownControllerManager getInstance() {
        return mInstance;
    }

    public void registerAll() {
        // 注册监听网络连接
        EZAndroidApplication.gContext.registerReceiver(mNetworkChangedReceiver,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        for (IDownController downController : mDownControllers) {
            downController.register();
        }
    }

    private void dealWifi() {
        for (IDownController downController : mDownControllers) {
            downController.startDown();
        }
    }

    private void dealGPRS() {
        for (IDownController downController : mDownControllers) {
            if (downController.canDownWithoutWifi()) {
                downController.startDown();
            } else {
                downController.pauseDown();
            }
        }
    }

    private void dealWithoutInternet() {
        for (IDownController downController : mDownControllers) {
            downController.pauseDown();
        }
    }

    public void unregisterAll() {
        for (IDownController downController : mDownControllers) {
            downController.unregister();
        }
        mDownControllers.clear();
        // 注销监听网络连接
        EZAndroidApplication.gContext.unregisterReceiver(mNetworkChangedReceiver);
    }
}
